package com.soxing.webrain.brush.service;

import com.mathworks.toolbox.javabuilder.MWCellArray;
import com.mathworks.toolbox.javabuilder.MWCharArray;
import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import com.soxing.webrain.brush.api.IUserEegHandleService;
import com.soxing.webrain.brush.common.config.SystemConfig;
import com.soxing.webrain.brush.domain.view.Eeg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import wb_loadEEG.WbPopLoadSet;



import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("userEegHandleService")
public class UserEegHandleServiceImpl implements IUserEegHandleService {


    /**
     * private String EEGfile = "E:/寒假工作/wb_test/EEG/TEST_data/lxl_s1_prepro_ERP.zip";
     * 必须在服务器中定义一个临时存放数据的文件夹
     * private String unzip_dir = "";
     */
    //private static String beforeUnzip = "/export/data/combs.uestc.edu.cn/unzip/";

    @Resource
    private SystemConfig systemConfig;

    @Override
    public Eeg packageData(Integer starttime, Integer endtime, String EEGfile) {
        WbPopLoadSet w = null;

        int indexUnzip = EEGfile.indexOf("/");
        for (int i = 0; i < 4; i ++) {
            indexUnzip = EEGfile.indexOf('/',indexUnzip + 1);
        }

        String tmpdir = EEGfile.substring(indexUnzip + 1);
        tmpdir = StringUtils.substringBeforeLast((systemConfig.getBeforeUnzip() + tmpdir), "/") + "/unzip";

        // 不存在就创建一个解压文件夹
        File unzip = new File(tmpdir);
        if (!unzip.exists()) {
            unzip.mkdir();
        }

        String unzip_dir = unzip.getPath();
        log.info(unzip_dir);

        try {
            w = new WbPopLoadSet();
        } catch (MWException e) {
            e.printStackTrace();
        }
        Object[] result = null;

        try {
            result = w.wb_loadEEG(18, EEGfile, unzip_dir);
        } catch (MWException e) {
            e.printStackTrace();
        }

        MWNumericArray temp = (MWNumericArray) result[1];
        double[][] data = (double[][]) temp.toDoubleArray();

        temp = (MWNumericArray) result[2];
        double[][] srate = (double[][]) temp.toDoubleArray();

        String ref = (String) result[3].toString();

        MWCellArray temp1 = (MWCellArray) result[4];
        String event_type = temp1.toString();

        temp = (MWNumericArray) result[5];
        double[][] event_latency = (double[][]) temp.toDoubleArray();

        MWCharArray temp2 = (MWCharArray) result[6];
        String labels = (String) temp2.toString();

        temp = (MWNumericArray) result[7];
        double[][] sph_radius = (double[][]) temp.toDoubleArray();

        temp = (MWNumericArray) result[8];
        double[][] sph_theta = (double[][]) temp.toDoubleArray();

        temp = (MWNumericArray) result[9];
        double[][] phi = (double[][]) temp.toDoubleArray();

        temp = (MWNumericArray) result[10];
        double[][] theta = (double[][]) temp.toDoubleArray();

        temp = (MWNumericArray) result[11];
        double[][] radius = (double[][]) temp.toDoubleArray();

        temp = (MWNumericArray) result[15];
        double[][] xmin = (double[][]) temp.toDoubleArray();

        temp = (MWNumericArray) result[16];
        double[][] xmax = (double[][]) temp.toDoubleArray();


        //0. ---------------- 定义数据存储的对象
        Eeg eeg = new Eeg();


        //2. ----------------- data 数据处理

        List<List<Double>> groupdata = new ArrayList<List<Double>>();
        for (int i = 0; i < data.length; i++) {
            List datas = new ArrayList();
            int s = (int) (1000 / srate[0][0]);
            for (int j = (int) (starttime * srate[0][0]); j < endtime * srate[0][0]; j++) {
                if (j == data[0].length) {
                    break;
                } else {
                    datas.add(data[i][j]);
                }

            }
            groupdata.add(datas);
        }

        //3. ----------------- labels(数据chanlocs可能不存在 分开分析) 数据处理


        List<String> grouplabel = new ArrayList();
        if (labels != null) {
           grouplabel = formatData(labels);
        } else {
            for (int i = 1; i < data.length; i++) {
                grouplabel.add(i + "");
            }
        }


        //4.---------------- event_type(两种类型字符串或者数组) 数据处理

        if (event_type.contains("[")) {
            String[] tp = event_type.split("[\\[\\]]");
            //------- 对label进行整理  定义集合
            List<String> tp1 = new ArrayList();
            for (int i = 0, j = 0; i < tp.length; i++) {
                if (i % 2 != 0) {
                    tp1.add(tp[i]);
                }
            }
            eeg.setEvent_type(tp1);

        } else {

            String[] tp = event_type.split("'"); //la的长度为 labels的二倍
            List<String> tp1 = new ArrayList(); //定义一个用于存放
            for (int i = 1, index = 0; i < tp.length; index++) {
                tp1.add(tp[i]);
                i = i + 2;
            }
            eeg.setEvent_type(tp1);
        }

        //5. ---------------- event_latency 标线时间点 数据处理

        //5.1 --------------- event_latency 为空判断
        double[] evtls = null;
        if (event_latency.length != 0) {
            evtls = event_latency[0];
        }else {
            evtls = new double[]{1};
        }


        //6. ---------------- srate 数据处理
        double[] sraten = srate[0];


        //7. ---------------- 电极坐标theta radius的数值  数据处理

        //7.1 --------------- theta 判空
        double[] thetan = null;
        if (theta.length != 0) {
            thetan = theta[0];
        }

        //7.2 ---------------- radius 判空
        double[] radiusn = null;
        if (radius.length != 0) {
            radiusn = radius[0];
        }


        //8. -------------------- 最小值（判断是erp数据还是eeg数据）
        double[] xminn = xmin[0];

        //9. -------------------- 最大值
        double[] xmaxn = xmax[0];

        //10. -------------------- time（传输starttime 和 endtime）数据处理
        List time = new ArrayList();
        for (int i = 0; i <= 10 * srate[0][0]; i++) {
            time.add(starttime + 0.001 * i * 1000 / srate[0][0]);
        }

        // ============== 数据存储
        eeg.setData(groupdata);
        eeg.setSrate(sraten);
        eeg.setRef(ref);
        eeg.setEvent_latency(evtls);
        eeg.setLabels(grouplabel);
        eeg.setTheta(thetan);
        eeg.setRadius(radiusn);
        eeg.setXmin(xminn);
        eeg.setXmax(xmaxn);
        eeg.setTime(time);


        return eeg;
    }


    //格式数据
    public List<String> formatData(String labels) {

        String[] la = labels.split("\n"); //la的长度为 labels的二倍
        List<String> grouplabel = new ArrayList(); //定义一个用于存放
        for (int index = 0; index < la.length; index++) {
            grouplabel.add(la[index]);
            //i = i + 2;
        }
        return grouplabel;
    }

}
